import { useState, useEffect } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  TextField,
  Box,
  CircularProgress,
  Alert,
} from '@mui/material';
import { DateTimePicker } from '@mui/x-date-pickers/DateTimePicker';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { zhCN } from 'date-fns/locale';
import { PromotionService, Promotion } from '../services/PromotionService';
import { useAuth } from '../../auth/AuthContext';

interface PromotionFormProps {
  open: boolean;
  onClose: () => void;
  onSaveSuccess?: () => void;
  promotion?: Promotion; // 如果提供，则为编辑模式
}

const PromotionForm = ({ open, onClose, onSaveSuccess, promotion }: PromotionFormProps) => {
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [imageUrl, setImageUrl] = useState('');
  const [startTime, setStartTime] = useState<Date | null>(null);
  const [endTime, setEndTime] = useState<Date | null>(null);
  const [points, setPoints] = useState('');
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const { user } = useAuth();

  useEffect(() => {
    if (promotion) {
      setTitle(promotion.title);
      setDescription(promotion.description);
      setImageUrl(promotion.imageUrl);
      setStartTime(new Date(promotion.startTime));
      setEndTime(new Date(promotion.endTime));
      setPoints(promotion.points.toString());
    } else {
      resetForm();
    }
  }, [promotion]);

  const resetForm = () => {
    setTitle('');
    setDescription('');
    setImageUrl('');
    setStartTime(null);
    setEndTime(null);
    setPoints('');
    setError(null);
  };

  const validateForm = () => {
    if (!title.trim()) {
      setError('请输入活动标题');
      return false;
    }
    if (!startTime) {
      setError('请选择开始时间');
      return false;
    }
    if (!endTime) {
      setError('请选择结束时间');
      return false;
    }
    if (startTime >= endTime) {
      setError('结束时间必须晚于开始时间');
      return false;
    }
    if (!points || isNaN(Number(points)) || Number(points) <= 0) {
      setError('请输入有效的积分奖励');
      return false;
    }
    return true;
  };

  const handleSubmit = async () => {
    if (!user || !validateForm()) return;

    try {
      setSaving(true);
      setError(null);

      const promotionData = {
        title: title.trim(),
        description: description.trim(),
        imageUrl: imageUrl.trim(),
        startTime: startTime!.toISOString(),
        endTime: endTime!.toISOString(),
        points: Number(points),
        creatorId: user.id,
        creatorName: user.username,
      };

      if (promotion) {
        await PromotionService.updatePromotion(promotion.id, promotionData);
      } else {
        await PromotionService.createPromotion(promotionData);
      }

      onSaveSuccess?.();
      handleClose();
    } catch (err) {
      setError(err instanceof Error ? err.message : (promotion ? '更新活动失败' : '创建活动失败'));
    } finally {
      setSaving(false);
    }
  };

  const handleClose = () => {
    resetForm();
    onClose();
  };

  return (
    <LocalizationProvider dateAdapter={AdapterDateFns} adapterLocale={zhCN}>
      <Dialog open={open} onClose={handleClose} maxWidth="sm" fullWidth>
        <DialogTitle>{promotion ? '编辑活动' : '创建活动'}</DialogTitle>
        <DialogContent>
          <Box sx={{ pt: 2 }}>
            {error && (
              <Alert severity="error" sx={{ mb: 2 }}>
                {error}
              </Alert>
            )}
            <TextField
              fullWidth
              label="活动标题"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              required
              disabled={saving}
              sx={{ mb: 2 }}
            />
            <TextField
              fullWidth
              label="活动描述"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              multiline
              rows={4}
              disabled={saving}
              sx={{ mb: 2 }}
            />
            <TextField
              fullWidth
              label="活动图片URL"
              value={imageUrl}
              onChange={(e) => setImageUrl(e.target.value)}
              placeholder="https://example.com/image.jpg"
              disabled={saving}
              sx={{ mb: 2 }}
            />
            <DateTimePicker
              label="开始时间"
              value={startTime}
              onChange={setStartTime}
              disabled={saving}
              sx={{ mb: 2, width: '100%' }}
            />
            <DateTimePicker
              label="结束时间"
              value={endTime}
              onChange={setEndTime}
              disabled={saving}
              sx={{ mb: 2, width: '100%' }}
            />
            <TextField
              fullWidth
              label="积分奖励"
              type="number"
              value={points}
              onChange={(e) => setPoints(e.target.value)}
              required
              disabled={saving}
              inputProps={{ min: 1 }}
            />
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleClose} disabled={saving}>
            取消
          </Button>
          <Button
            onClick={handleSubmit}
            disabled={saving}
            variant="contained"
            startIcon={saving ? <CircularProgress size={20} /> : undefined}
          >
            {saving ? '保存中...' : '保存'}
          </Button>
        </DialogActions>
      </Dialog>
    </LocalizationProvider>
  );
};

export default PromotionForm;